import Taro from '@tarojs/taro'
import { baseUrl } from '../config/index'
const baseOptions = (params, method = 'GET') => {
    const { url, data } = params
    let contentType = 'application/json'
    contentType = params.contentType || contentType

    const header = {
        'content-type': contentType,
    }
    const option = {
        // url: url.indexOf('http') !== -1 ? url : (baseUrl + '/api' + url),
        url: baseUrl + url,
        data: data,
        method: method,
        header,
        xhrFields: { withCredentials: true },
        success(res) {
            const { statusCode, data } = res
            if (statusCode === 200) {
                return res.data
            }
            if (statusCode === 401) {
                goLogin()
                return
            }
            Taro.showToast({ title: data.message || '未知错误', icon: 'error' })
        },
        error(e) {
            Taro.showToast({ title: e || '未知错误', icon: 'error' })
        }
    }
    return Taro.request(option)
}

const goLogin = () => {
    Taro.showToast({ title: '请先登录', icon: 'none' })
    Taro.clearStorage()
    Taro.reLaunch({
        url: '/pages/login/login'
    })
}

export const get = (url, data) => {
    const params = { url, data }
    return baseOptions(params)
}
export const post = (url, data, contentType) => {
    const params = { url, data, contentType }
    return baseOptions(params, 'POST')
}
export const put = (url, data) => {
    return baseOptions({ url, data }, 'PUT')
}
export const del = (url, data) => {
    return baseOptions({ url, data }, 'DELETE')
}

